package cn.itcast.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.UUID;

import cn.itcast.bean.Users;


public class JdbcUtils {
	public static String url = null ;
	public static String username = null ;
	public static String password = null ;
		
	static {
		try {
			InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
			Properties prop = new Properties();		
			prop.load(in);
			
			String driver = prop.getProperty("driver");
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			
			Class.forName(driver);
		} catch (Exception e) {
			  e.printStackTrace();
		}
	}
	
	
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, username, password);
	}
	public static String  makeId() {
		return UUID.randomUUID().toString();
	}
	public static void release(Connection conn,Statement st,ResultSet rs){
		
		
		if(rs!=null){
			try{
				rs.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
			rs = null;

		}
		if(st!=null){
			try{
				st.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		if(conn!=null){
			try{
				conn.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}
	
	public static boolean add(String sql, Object... params) {
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try{
			conn = JdbcUtils.getConnection();
			st = conn.prepareStatement(sql);
			if(params != null) {
				for (int i = 1; i <= params.length; i++) {
					st.setObject(i, params[i-1]);
				}
			}
		if(st.executeUpdate() == 1) {
			return true;
		}else {
			return false;
		}
		
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			JdbcUtils.release(conn, st, rs);
		}
	}
	
	public static void find(String sql,Object...params) {
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try{
			conn = JdbcUtils.getConnection();
			st = conn.prepareStatement(sql);
			if(params != null) {
				for (int i = 1; i <= params.length; i++) {
					st.setObject(i, params[i-1]);
				}
			}
		 st.executeQuery() ;
	
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			JdbcUtils.release(conn, st, rs);
		}
	}
	
	
}
